package com.wisezone.springmvc.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.channels.FileChannel;

public class FileUtils {
	
	/**
	 * 
	 * 创建文件
	 * 
	 * @param pathFile
	 *            E:\\java1707\\java_collection\\set\\myHashSet.java
	 * @throws IOException
	 * 
	 */
	public static void createFile(String pathFile) {
		if (pathFile == null || "".equals(pathFile)) {
			throw new NullPointerException("创建文件路径不能为null或空字符串");
		}
		int lastIndex = pathFile.lastIndexOf("\\"); // 获取倒数第一个分隔符序号
		String dir = pathFile.substring(0, lastIndex); // 切割字符串 dir:E:\\java1707\\java_collection\\set\\

		File directFile = new File(dir); // 构造目录File对象
		if (!directFile.exists()) // 判断目录是否存在
			directFile.mkdirs(); // 递归创建目录

		File file = new File(pathFile); // 构造文件File对象
		if (!file.exists())
			try {
				file.createNewFile();
			} catch (IOException e) {
				System.out.println("文件创建失败");
			} // 创建文件File
	}

	public static void createFile(File file) {
		createFile(file.getPath());
	}

	/**
	 * 删除文件或目录
	 * 
	 * @param pathFile
	 *            : E:\java1707\java_collection\set\myHashSet.java
	 */
	public static void deleteFile(File pathFile) {
		File[] fileLists = pathFile.listFiles();

		for (File file : fileLists) {
			if (file.isFile()) {
				file.delete();
			}
			if (file.isDirectory()) {
				deleteFile(file);
			}
		}
		pathFile.delete();
	}

	public static void deleteFile(String pathFile) {
		deleteFile(new File(pathFile));
	}

	/**
	 * 递归遍历文件目录
	 * 
	 * E:\java1707 File dirFile = new File("E:\java1707"); 显示E:\java1707目录下所有文件名
	 */
	public static void seacherFile(File dirFile) {
		File[] fileLists = dirFile.listFiles();
		for (File file : fileLists) {
			if (file.isFile()) {
				System.out.println(file.getAbsolutePath());
			}
			if (file.isDirectory()) {
				seacherFile(file);
			}
		}
	}

	public static void seacherFile(String dir) {
		File dirFile = new File(dir);
		seacherFile(dirFile);
	}

	public static void copyFileNio(String src, String dist) {
		File newFile = new File(dist);
		if (!newFile.exists()) {
			createFile(dist);
		}
		copyFileNio(new File(src), newFile);
	}

	/**
	 * 复制文件
	 * 
	 * @param oldFile
	 *            E:\\java1707\bb1.txt
	 * @param newFile
	 *            D:\\java1707\bb1.txt
	 * 
	 *            原理: 从原文件oldFile读取数据写入newFile
	 */
	public static void copyFileNio(File oldFile, File newFile) {
		FileInputStream in = null;
		FileOutputStream os = null;
		FileChannel inChannel = null, osChannel = null;
		try {
			in = new FileInputStream(oldFile); // 文件输入流，与原文件关联
			os = new FileOutputStream(newFile); // 文件输出流,与新文件关联

			inChannel = in.getChannel();
			osChannel = os.getChannel();

			inChannel.transferTo(0, inChannel.size(), osChannel);

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (inChannel != null)
					inChannel.close();
				if (osChannel != null)
					osChannel.close();
				if (in != null)
					in.close();
				if (os != null)
					os.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 文件复制
	 * 
	 * @param oldFile
	 * @param newFile
	 */
	public static void copyFile(File oldFile, File newFile) {
		InputStream in = null;
		OutputStream os = null;
		try {
			in = new FileInputStream(oldFile); // 文件输入流，与原文件关联
			os = new FileOutputStream(newFile); // 文件输出流,与新文件关联

			byte[] bytes = new byte[128]; // 缓冲区
			int len = 0;
			while ((len = in.read(bytes)) != -1) {
				os.write(bytes, 0, len);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (in != null)
					in.close();
				if (os != null)
					os.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 文件复制
	 */
	public static void copyFile(String oldpath, String newpath) {
		File newFile = new File(newpath);
		if (newFile.exists() == false) {
			createFile(newpath);
		}
		copyFile(new File(oldpath), newFile);
	}
	public static String cacheRootDir = "E://cache/";
	public static void writeFile(String fileName,String content) {
		File file = new File(cacheRootDir,fileName);
		if(file.exists() == false) {
			createFile(file);
		}
		OutputStream os = null;
		try {
			os = new FileOutputStream(file); // 文件输出流,与新文件关联
			os.write(content.getBytes());
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (os != null)
					os.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	 /**
     * 以行为单位读取文件，常用于读面向行的格式化文件
     */
    public static String readFileByLines(String fileName) {
    	File file = new File(cacheRootDir,fileName);
		if(file.exists() == false) {
			return "";
		}
		
        BufferedReader reader = null;
        StringBuilder sb = new StringBuilder();
        try {
            reader = new BufferedReader(new FileReader(file));
            String tempString = null;
            // 一次读入一行，直到读入null为文件结束
            while ((tempString = reader.readLine()) != null) {
                sb.append(tempString);
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                }
            }
        }
        return sb.toString();
    }

	public static void main(String[] args) {
//		copyFileNio("E:\\java1707\\bb.txt", "D:\\kk.txt");
		StringBuilder sb = new StringBuilder();
		System.out.println("sb :"+sb.toString());
	}
}
